// Copyright (C) 2012 Yoshiki Shibata. All rights reserved.
package main

import "fmt"
import "os"
import "bufio"
import "strings"

func main() {
	fmt.Printf("MessagingTool implemented with Go (V0.00)\n")
	fmt.Printf("Copyright (C) 2012 Yoshiki Shibata. All rights reserved.\n")

	reader := bufio.NewReader(os.Stdin)
	userName := getUserName(reader);

	msgChan := make(chan RxMessage)
	go showMessage(msgChan)
	listener := NewChatListener()
	listener.AddMessageChannel(msgChan)
	go listener.Start()	
	sender := NewChatSender(userName)
	for {
		recipients := strings.Split(getRecipients(reader), ",");
		message := getMessage(reader);
        results := sender.Send(recipients, message)	
        for i := 0; i < len(results); i++ {
            if results[i] {
                fmt.Printf("%s(success)", recipients[i])
            } else {
                fmt.Printf("%s(failure)", recipients[i])
            }
            if i != 0 && i < (len(results) - 1){
                    fmt.Printf(", ")
            }
        }
        fmt.Printf("\n")
	}
}

func readString(reader *bufio.Reader) string {
	// Following reader.ReadString reads input until '\n' is found.
	// But note that returned string contains '\n'
	// So get rid of '\n' as well as '\r'(for Windows)
	input, _ := reader.ReadString('\n')
	trimedInput := strings.Trim(input, "\n\r")	
	return trimedInput
}

func getUserName(reader *bufio.Reader)string{
	fmt.Printf("Your name: ")
    return readString(reader);
}

func getRecipients(reader *bufio.Reader) string {
	fmt.Printf("IP address of recipients: ")
    return readString(reader);
}

func getMessage(reader *bufio.Reader) string {
	fmt.Printf("Message: ")
    return readString(reader);
}

func showMessage(msgChan chan RxMessage) {
	for {
		msg := <- msgChan
		fmt.Printf("[Version = %d, From: %s(%s), To: %s Msg: %s]\n", 
						msg.message.Version, msg.message.From, 
                        msg.remoteAddr,
                        msg.message.To, msg.message.Message)
	}
}
